package com.longteng.testng.binder;

import com.longteng.testng.MethodParam;
import com.longteng.testng.annotation.Bean;
import com.longteng.testng.annotation.Binding;
import com.longteng.testng.param.Pair;
import jodd.bean.BeanUtil;
import org.apache.commons.lang3.StringUtils;

import java.util.List;

/**
 * Created by sky on 15-12-24
 */
@Binding
public class BeanBindPlugin extends BindPlugin{

    @Override
    public Object transfer(List<Pair> pairs, MethodParam parameter) {
        if(pairs==null||pairs.size()==1){
            throw new RuntimeException("参数名称和参数化文件匹配项个数不一致");
        }
        try{
            Class<?> clz = parameter.getType();
            Object object = clz.newInstance();
            pairs.forEach(pair -> BeanUtil.setPropertyForced(object,
                    StringUtils.substring(pair.getKey(),parameter.getName().length()+1),pair.getValue()));
            return object;
        }catch (Exception e){
            throw new RuntimeException(e);
        }

    }

    @Override
    public boolean filter(MethodParam parameter) {
        Bean bean = parameter.getAnnotation(Bean.class);
        if(bean==null){
            return false;
        }
        return true;
    }
}
